import {
  WEBSOCKET_URL
} from '../../common/common';
const event = require('./event.js');
export default class WebSocketService {
  constructor() {
    this.socketTask = null;
    this.userId = null
  }
  reConnect(userId) {
    if (this.socketTask && this.socketTask.readyState === 1) {
      return this.socketTask;
    } else {
      this.connect(userId);
      return this.socketTask;
    }
  }

  connect(userId) {
    this.userId = userId
    this.socketTask = wx.connectSocket({
      url: WEBSOCKET_URL,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log('WebSocket连接成功');
      },
      fail: function (err) {
        console.log('WebSocket连接失败', err);
      }
    });
    console.log(this.socketTask)
    console.log(this.socketTask.readyState)
    this.socketTask.onOpen(() => {
      console.log('WebSocket 已连接');
      this.preSend();
    });
    this.socketTask.onMessage(function (res) {
      // console.log('收到服务器内容：' + res.data);
      event.emit('websocketMessage', JSON.parse(res.data));
    });
    this.socketTask.onClose(function (res) {
      console.log('WebSocket 已关闭！');
    });
    this.socketTask.onError(function (err) {
      console.log('WebSocket 错误', err);
    });
  }

  preSend() {
    let message = {
      action: 'login',
      from: this.userId
    }
    this.send(message)
  }

  createGroup(toUserId) {
    let message = {
      from: this.userId,
      to: toUserId,
      action: 'create'
    }
    this.send(message)
  }

  send(data) {
    this.socketTask.send({
      data: JSON.stringify(data),
      success: function () {
        console.log('消息发送成功');
      },
      fail: function (err) {
        console.log('消息发送失败', err);
      }
    });
  }

  close() {
    this.socketTask.close();
  }

}